<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>客户管理</el-breadcrumb-item>
      <el-breadcrumb-item>供应商列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getProvidersList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getProvidersList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加供应商</el-button
          >
        </el-col>
        <el-button type="primary" @click="exportExcel"
          >点击导出表格数据</el-button
        >
        <el-button type="primary" v-if="!map" @click="map = true"
          >点击展示地图</el-button
        >
        <el-button type="danger" v-else @click="map = false"
          >点击关闭地图</el-button
        >
      </el-row>

      <baidu-map
        v-show="map"
        class="bm-view"
        :center="{ lng: 120.378386, lat: 30.309756 }"
        :zoom="20"
        :scroll-wheel-zoom="true"
      >
        <bm-marker
          :position="{ lng: 120.378386, lat: 30.309756 }"
          :dragging="true"
          animation="BMAP_ANIMATION_BOUNCE"
        />
      </baidu-map>
      <!-- 虚拟表格数据 -->
      <el-table
        :data="providersListForExport"
        border
        stripe
        id="out-table"
        v-show="false"
      >
        <el-table-column type="index"></el-table-column>
        <el-table-column
          label="供应商名称"
          prop="provider_name"
        ></el-table-column>
        <el-table-column
          label="地址"
          prop="provider_address"
          width="450px"
        ></el-table-column>
        <el-table-column
          label="电话"
          prop="provider_phone"
          width="120px"
        ></el-table-column>
        <el-table-column
          label="供应货物"
          prop="provider_good"
          width="150px"
        ></el-table-column>
      </el-table>
      <!-- 表格数据 -->
      <el-table :data="providersList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column
          label="供应商名称"
          prop="provider_name"
        ></el-table-column>
        <el-table-column
          label="地址"
          prop="provider_address"
          width="450px"
        ></el-table-column>
        <el-table-column
          label="电话"
          prop="provider_phone"
          width="120px"
        ></el-table-column>
        <el-table-column
          label="供应货物"
          prop="provider_good"
          width="150px"
        ></el-table-column>
        <el-table-column label="操作" width="130px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.provider_id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeById(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      ></el-pagination>
    </el-card>
    <!-- 添加供应商的对话框 -->
    <el-dialog
      title="添加供应商"
      :visible.sync="addDialogVisible"
      width="50%"
      @closed="addDialogClosed"
    >
      <!-- 内容区 -->
      <el-form
        :model="addForm"
        :rules="providerRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item
          label="供应商名称"
          prop="provider_name"
          label-width="100px"
        >
          <el-input v-model="addForm.provider_name"></el-input>
        </el-form-item>
        <el-form-item label="省市区" label-width="100px">
          <el-cascader
            v-model="headAddress"
            :options="cityData"
            :props="{ expandTrigger: 'hover' }"
            filterable
            clearable
            @change="selectChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item
          label="详细地址"
          prop="provider_address"
          label-width="100px"
        >
          <el-input v-model="addForm.provider_address"></el-input>
        </el-form-item>
        <el-form-item
          label="供应商电话"
          prop="provider_phone"
          label-width="100px"
        >
          <el-input v-model="addForm.provider_phone"></el-input>
        </el-form-item>
        <el-form-item label="供应货物" prop="provider_good" label-width="100px">
          <el-input v-model="addForm.provider_good"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addProvider"> 确 定 </el-button>
      </span>
    </el-dialog>
    <!-- 修改供应商信息的对话框 -->
    <el-dialog
      title="修改供应商信息"
      :visible.sync="editDialogVisible"
      width="50%"
    >
      <!-- 内容区 -->
      <el-form
        :model="editForm"
        :rules="providerRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item
          label="供应商名称"
          prop="provider_name"
          label-width="100px"
        >
          <el-input v-model="editForm.provider_name"></el-input>
        </el-form-item>
        <el-form-item
          label="供应商地址"
          prop="provider_address"
          label-width="100px"
        >
          <el-input v-model="editForm.provider_address"></el-input>
        </el-form-item>
        <el-form-item
          label="供应商电话"
          prop="provider_phone"
          label-width="100px"
        >
          <el-input v-model="editForm.provider_phone"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editProductInfo"> 确 定 </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script type="text/javascript">
//引入地址数据
import cityData from '../order/cityData.js'

// 引入导出Excel表格依赖
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
  data() {
    // 自定义验证手机规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^((13[0-9])|(17[0-1,6-8])|(15[^4,\\D])|(18[0-9]))\d{8}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }
    return {
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 10
      },
      //控制地图显示
      map: false,
      // 供应商列表
      providersList: [],
      //用于导出的表格数据
      providersListForExport: [],
      //城市列表
      cityData,
      //地址头部信息
      headAddress: '',
      // 供应商总数
      total: 0,
      // 控制添加供应商对话框的显示与隐藏
      addDialogVisible: false,
      // 添加供应商的表单数据
      addForm: {
        provider_name: '',
        provider_address: '',
        provider_phone: '',
        provider_good: ''
      },
      // 控制修改供应商对话框的显示与隐藏
      editDialogVisible: false,
      //修改表单信息
      editForm: {},
      //修改表单的验证规则对象
      providerRules: {
        provider_name: [
          {
            required: true,
            message: '请输入供应商名称',
            trigger: 'blur'
          }
        ],
        provider_address: [
          {
            required: true,
            message: '请输入供应商地址',
            trigger: 'blur'
          }
        ],
        headAddress: [
          {
            required: true,
            message: '请输入供应商地址',
            trigger: 'blur'
          }
        ],
        provider_phone: [
          {
            required: true,
            message: '请输入供应商电话',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ],
        provider_good: [
          {
            required: true,
            message: '请输入供应商供应货品',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getProvidersList()
  },
  mounted() {},
  methods: {
    // 根据分页获取对应的供应商列表
    async getProvidersList() {
      const { data: res } = await this.$http.get('allProvider', {
        params: this.queryInfo
      })
      if (res.numbers < 1) {
        return this.$message.error('获取供应商列表失败！')
      }
      this.providersList = res.data
      console.log(this.providersList)
      this.total = res.numbers
      const { data: res2 } = await this.$http.get('allProviders')
      this.providersListForExport = res2.data
    },
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getProvidersList()
    },
    handleCurrentChange(newSize) {
      this.queryInfo.pageNum = newSize
      this.getProvidersList()
    },
    // 展示供应商编辑的对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('getUpdateProvider?id=' + id)
      console.log(res)
      if (res == null) {
        return this.$message.error('查询供应商信息失败！')
      }
      this.editForm = res
      this.editDialogVisible = true
    },
    // 监听添加供应商对话框的关闭事件
    addDialogClosed() {
      // 重置表单项
      this.$refs.addFormRef.resetFields()
      this.headAddress = ''
    },
    selectChange() {
      console.log('hahah')
      //将级联选择器选中的数组变成字符串
      var str = ''
      for (let i = 0; i < this.headAddress.length; i++) {
        str += this.headAddress[i]
      }
      //地址信息赋值给详细信息
      this.addForm.provider_address = str
    },
    //添加供应商
    addProvider() {
      //发起添加供应商请求+
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post('addProvider', this.addForm)
        if (res !== 'success') {
          return this.$message.error('添加供应商失败')
        }
        this.$message.success('添加供应商成功')
        // 隐藏添加供应商对话框，先关闭窗口避免一瞬间尴尬~~~~
        this.addDialogVisible = false
        // 重新获取供应商列表数据
        this.getProvidersList()
      })
    },
    //修改供应商信息并提交
    editProductInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        //发起修改供应商信息的数据请求
        const { data: res } = await this.$http.put(
          'editProvider',
          this.editForm
        )
        if (res !== 'success') {
          return this.$message.error('修改数据失败！')
        }
        //关闭对话框
        this.editDialogVisible = false
        //刷新供应商数据列表
        this.getProvidersList()
        //提示修改成功
        this.$message.success('修改数据成功！')
      })
    },
    // 通过Id删除供应商
    async removeById(provider) {
      //删除之前先判断商品库中是否还存在该商品
      const { data: res2 } = await this.$http.get('allProducts')
      var productList = res2.data
      console.log(provider, 'provider')
      console.log(productList, 'productList')
      for (let item of productList) {
        if (item.productName == provider.provider_good) {
          return this.$message({
            showClose: true,
            message: '请先删除商品库中该供应商提供的商品！',
            type: 'error'
          })
        }
      }
      const confirmResult = await this.$confirm(
        '此操作将永久删除该供应商, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      const { data: res } = await this.$http.delete(
        'deleteProvider?id=' + provider.provider_id
      )
      if (res !== 'success') {
        return this.$message.error('删除供应商失败!')
      }
      this.$message.success('删除供应商成功!')
      this.getProvidersList()
    },
    exportExcel() {
      /* 从表生成工作簿对象 */
      var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'))
      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      try {
        FileSaver.saveAs(
          //Blob 对象表示一个不可变、原始数据的类文件对象。
          //Blob 表示的不一定是JavaScript原生格式的数据。
          //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
          //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
          new Blob([wbout], { type: 'application/octet-stream' }),
          //设置导出文件名称
          '导出数据文件.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    }
  }
}
</script>

<style lang="less" scoped>
.bm-view {
  margin-top: 20px;
  margin-bottom: 20px;
  width: 100%;
  height: 500px;
}
</style>
